package string;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author Yi Jun jie
 * @Date 2021/3/2 14:15
 * 面试题 01.06. 字符串压缩
 */
public class LeetCode0106 {
    public static void main(String[] args) {
        System.out.println(new Solution0106().compressString("aabcccccaa"));
    }
}

class Solution0106 {
    //StingBuilder 对代码效率的影响特别大(几十倍)
    public String compressString(String S) {
        if (S == null || S.length() == 0) return "";
        StringBuilder res = new StringBuilder();
        char[] chars = (S+' ').toCharArray();
        char r = chars[0]; int num = 0;
        for(char c: chars) {
            if(c == r) {
                num ++;
            } else {
                res.append(r).append(num);
                r = c;
                num = 1;
            }
        }
        return S.length() <= res.length()? S: res.toString();
    }
}

// 网上答案和我写的基本一样 StringBuilder 要快一些(这里我如果使用 StringBuilder 效率比他高)
class Solution0106Plus {
    public String compressString(String S) {
        // 判空
        if (S == null || S.length() == 0) return "";
        char[] arr = S.toCharArray();
        char c = arr[0];
        int n = 1;
        StringBuilder res = new StringBuilder();
        for (int i = 1; i < arr.length; i++) {
            if (c == arr[i]) {
                n++;
            } else {
                res.append("" + c + n);
                c = arr[i];
                n = 1;
            }
        }
        res.append("" + c + n);
        return res.toString().length() < S.length() ? res.toString() : S;
    }
}